var http=require('http');
var url=require('url');
var items=['First','Second'];

var server=http.createServer(function (req, res) {
    switch(req.method){
        case 'GET':
            var body='';
            items.forEach(function (item, i) {
                body+=i+') '+item+'\n';
            });
            res.setHeader('Content-Type','text/plain;charset="utf-8"');
            res.setHeader('Content-Length',Buffer.byteLength(body));
            res.end(body);
            break;

        case 'POST':
            var item='';
            req.setEncoding('utf8');
            req.on('data',function (chunk) {
                item+=chunk;
            });
            req.on('end',function () {
                items.push(item);
            });
            res.end('ok');
            break;

        case 'DELETE':
            var pathname=url.parse(req.url).pathname;
            var i=parseInt(pathname.slice(1),10);
            if(isNaN(i)){
                res.statusCode=400;
                res.end('Invalid item id.');
            }else if(!items[i]){
                res.statusCode=404;
                res.end('Item not found.');
            }else{
                var item=items.splice(i,1)[0];
                res.end(item);
            }
            break;

        case 'PUT':
            var urlObj=url.parse(req.url,true);
            console.log(urlObj);
            var i=parseInt(urlObj.pathname.slice(1),10);
            var item=urlObj.query.item;

            if(isNaN(i)){
                res.statusCode=400;
                res.end('Invalid item id.');
            }else if(!items[i]){
                res.statusCode=404;
                res.end('Item not found.');
            }else{
                items[i]=item;
                res.end('OK');
            }

        default:
            res.end('default!!');
    }
});
server.listen(3000,function () {
    console.log('ToDoList 3000',new Date());
});
